Introduction to Promise function
Promise is a built in function with 2 arguments:
basic syntax of the promise() function is:
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('AfterTimeout');
}, 1000);
});
promise1.then(function(value) {
console.log(value);
});
console.log(promise1);
In this sample, the Promise function will run a setTimeout function
- If Promise succeeds, the .then function will run.
- If Promise failes, the .catch function will run.
the Promise function is asyncronous, therefore any action run by it will hapan after the regular code.
Promise with await
Vid 27 ~ 30:00
const getUser = cb => {
setTimeout(() => {
cb({
name: 'Max'
})
}, 2000)
}
getUser(user => {
console.log(user.name);
});
Loading external script
the next example shows how to add a link to external script in code, using promise function
function loadScript(src) {
const SCR = 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js'
return new Promise((resolve, reject) => {
let script = document.createElement('script');
script.src = src;
script.onload = () => resolve(script);
script.onerror = () =>
reject(new Error('Script load error:' + src));
document.head.append(script);
});
}
let promise =
loadScript('SCR');
promise.then(
script => alert(`${script.src} is loaded!`),
error => alert(`Error: ${error.message}`)
);
and with async & await
(
async() => {
try {
let script =
await loadScript(SCR);
alert(`${script.src} is loaded!`);
} catch (error) {
error => alert(`Error: ${error.message}`);
}
}
)();
//the func is wrapped with () and ran by ()
back to main page